/**
 * author:Administrator
 * date:2016/1/13
 * desc:TODO
 */
'use strict';

var Model = require('../model/user.js');
var Sequelize = require('sequelize');
var sequelize = require('../conn/sequelize.js');
var appUtil = require('../common/app_util.js');
var errCode = require('../common/err_code.js');

var dao = {};
module.exports = dao;

/**
 * create
 */
dao.create = function *(user) {
  var aUser = {
    name: user.name,
    email: user.email,
    password: user.password,
    roleid: user.roleid,
    createdAt: user.createdAt
  };
  try {
    var seqObj = yield Model.create(aUser);
    return appUtil.fout(seqObj.dataValues);
  } catch (err) {
    appUtil.logError('dao user error:', err);
    // 失败可能1, unique键重复
    var errMsg = 'in analyzing ...';
    if (err.toString().indexOf('SequelizeUniqueConstraintError') >= 0) {
      errMsg = '%s已被注册';
      errMsg = errMsg.replace('%s', JSON.stringify(err.fields));
      return appUtil.ferror(errCode.E_ARGS, errMsg);
    }
    // TODO 失败可能2
    // 无法判别的错误
    return appUtil.ferror(errCode.E_DB, 'user, ' + errMsg);
  }
};


/**
 * findOne
 */
dao.findOneByWhere = function* (where) {
  var seqObj = yield Model.findOne(where);
  return appUtil.fout(seqObj && seqObj.dataValues);
};